
package com.work;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.util.Factory;

import com.vaadin.annotations.*;
import com.vaadin.server.VaadinRequest;
import com.vaadin.ui.*;
import com.work.i18n.Messages;
import com.work.mvc.view.MainWindow;
import com.work.mvc.view.login.LoginWindow;
import com.work.servlets.InitDb;

@Theme("radek-theme")
@Title("WorkOvertime")
public class WorkovertimeApplication extends UI {

	private static final long serialVersionUID = 2517418006400033646L;

	private MainWindow mainWindow;
	private LoginWindow loginWindow = new LoginWindow();
	private HorizontalLayout appLayout = new HorizontalLayout();
	
	private ProgressIndicator progress = new ProgressIndicator();

	@Override
	protected void init(VaadinRequest request)
	{
		Messages.setLocale(getLocale());
		initUI();
		InitDb.createWorkDays();
	}
	
	private void initUI() {
		progress.setIndeterminate(true);
		this.addWindow(loginWindow);
		this.setContent(appLayout);
		appLayout.setSizeFull();
		appLayout.addComponent(progress);
		appLayout.setComponentAlignment(progress, Alignment.MIDDLE_CENTER);
		hideProgress();
	}

	public void logout()
	{
		getUI().getSession().close();
		SecurityUtils.getSubject().logout();

		loginWindow.center();
		loginWindow.setEnabled(true);
		loginWindow.setVisible(true);

		appLayout.removeComponent(mainWindow);
	}

	public void login()
	{
		showProgress();
		
		mainWindow = new MainWindow();

		loginWindow.setVisible(false);
		loginWindow.setEnabled(false);

		appLayout.addComponent(mainWindow);
		mainWindow.setSizeFull();
		
		hideProgress();
	}

	public void enableSecurity()
	{
		Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
		SecurityManager securityManager = factory.getInstance();
		SecurityUtils.setSecurityManager(securityManager);
	}
	
	public void hideProgress()
	{
		progress.setVisible(false);
		progress.setEnabled(false);
	}
	
	public void showProgress()
	{
		progress.setVisible(true);
		progress.setEnabled(true);
	}
}
